package db_main

import (
	"fmt"
	"gorm.io/gorm"
	global2 "longmen/server/config/global"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql/models/models_main"
	"reflect"
	"strings"
)

/*
*
@Create July07 2022 Enzo
通用方法，一般由worker调用，从队列中取出一个记录，插到库里
*/
func InsertLogDB(record interface{}) (int, error) {
	fName := "InsertLog"
	session := global2.GetX().Begin()
	logId, err := InsertLogByTx(session, record)
	if err != nil {
		global2.Log.Errorf("6InsertLog9%v写入失败", record)
		session.Rollback()
		return 0, fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	if err := session.Commit().Error; err != nil {
		session.Rollback()
		return 0, fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return logId, nil
}

/*
*
@Create July07 2022 Enzo
在库里南插入一个log记录;带上下文事务;
插入成功会返回ID
*/
func InsertLogByTx(session *gorm.DB, log interface{}) (int, error) {
	err := session.Create(log).Error
	if err != nil {
		global2.Log.Errorf("6InsertLogByTx9 error: %v", err)
		session.Rollback()
		return 0, err
	}
	vLog := reflect.ValueOf(log).Elem()
	iId := vLog.FieldByName("Id")
	if iId.Kind() == 0 {
		return 0, nil
	}
	return int(iId.Int()), nil
}

func InsertLogByOperateId(session *gorm.DB, operateId string, anchorProfit int) int64 {
	raw := session.Exec("insert into live.db_gift_log(giftid,anchorid,uid,liveid,count,spend,create_time,spend_type,anchor_profit,gift_type,actual_spend,remark,operate_id) select giftid,anchorid,uid,liveid,count,spend,now(),spend_type,?,gift_type,actual_spend,remark,operate_id from main.db_gift_log where operate_id=?", anchorProfit, operateId)
	if raw.Error != nil && strings.Index(raw.Error.Error(), "Duplicate entry") > 0 {
		return 999
	} else if raw.Error != nil {
		return 0
	}
	return raw.RowsAffected
}

func QueryByOperateId(operateId string) *models_main.GiftLog {
	var giftLog *models_main.GiftLog
	global2.GetX().Raw("select * from db_gift_log  where  operate_id=?", operateId).Scan(&giftLog)
	return giftLog
}
